package com.pen.interfece.controller.admin;


import com.pen.interfece.pojo.PageResult;
import com.pen.interfece.pojo.Result;
import com.pen.interfece.pojo.dto.AdminLoginDTO;
import com.pen.interfece.pojo.dto.AdminPageQueryDTO;
import com.pen.interfece.pojo.entity.Admin;
import com.pen.interfece.pojo.vo.AdminLoginVO;
import com.pen.interfece.service.AdminService;
import com.pen.interfece.util.JwtUtil;
import com.pen.interfece.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {

//test111
    @Autowired
    private AdminService adminService;
    @PostMapping("/login")

    public Result<AdminLoginVO> login(@RequestBody AdminLoginDTO adminLoginDTO){
        log.info("管理员登录");

        String account = adminLoginDTO.getAccount();
        String password = adminLoginDTO.getPassword();
        //调用service方法查询数据库
        Admin admin=adminService.login(adminLoginDTO);
        if(admin==null){
            return Result.error("账号不存在");
        }
        if(!admin.getPassword().equals(password)){
            return Result.error("密码错误");
        }
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("adminId", admin.getId());
        String token = JwtUtil.genToken(claims);

        AdminLoginVO adminLoginVO =new AdminLoginVO();
        BeanUtils.copyProperties(admin, adminLoginVO);
        adminLoginVO.setToken(token);
        System.out.println(adminLoginVO);
        return Result.success(adminLoginVO);
    }
    //新增管理员
    @PostMapping("/add")
    public Result save(@RequestBody Admin admin){
        log.info("新增员工：{}",admin);
        adminService.save(admin);

        return Result.success("增加成功");
    }

    //删除管理员
    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids)
    {
        log.info("管理员批量删除：{}",ids);
        adminService.deleteBatch(ids);
        return Result.success("删除成功");
    }
    @PutMapping
    public Result update(@RequestBody Admin admin){
        log.info("管理员修改：{}",admin);
        adminService.update(admin);
        return Result.success("修改成功");
    }

    @GetMapping("/page")
    public Result<PageResult> page(@RequestBody AdminPageQueryDTO adminPageQuerydto){
        log.info("员工分页查询：参数为：{}",adminPageQuerydto);
        PageResult pageResult=adminService.pageQuery(adminPageQuerydto);
        return Result.success(pageResult);
    }

}
